import React, { useState } from 'react';
import { Form, Input, Modal, Radio, Select,DatePicker,TreeSelect ,Space,Button,Steps} from 'antd';
const { Option } = Select;
const { TextArea } = Input;
const { Step } = Steps;
import { PlusOutlined,MinusCircleOutlined } from '@ant-design/icons';
import { validatorMobile } from '@/utils/utils';
import styles from '../index.less';
import moment from 'moment'
const FormItem = Form.Item;

let configItem=["commandPort","dataBits","baudRate","stopBits","parity","ipport"];
export interface UpdateFormProps {
  onCancel: () => void;
  onSubmit: (values: API.UserItem) => void;
  updateModalVisible: boolean;
  values: API.UserItem;
  devicetype:API.DictItem[];
  protocoltype:API.DictItem[];
  arealist:API.TreeNodeItem[];
  driverList?:API.DriverItem;
}

const formLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 15 },
};
const formItemLayout = {
  labelCol: { span: 0 },
  wrapperCol: { span: 24 },
};
const UpdateForm: React.FC<UpdateFormProps> = (props) => {

  

  const [formVals] = useState<API.DeviceItem>(props.values);
  const [form] = Form.useForm();
  const { updateModalVisible, onSubmit: handleUpdate,  onCancel,devicetype,arealist,protocoltype,driverList} = props;
  const [currentStep, setCurrentStep] = useState<number>(0);
  const [configRow,setConfigRow]= useState<number>(1);
  var sights=[];
  
  for(let driver of driverList){
    if(driver.id==formVals.driverId){
      if(driver.driverType==1){
        sights.push({value: driver.commandPort, key: 'commandPort'});
        sights.push({value: driver.dataBits, key: 'dataBits'});
        sights.push({value: driver.baudRate, key: 'baudRate'});
        sights.push({value: driver.stopBits, key: 'stopBits'});
        sights.push({value: driver.stopBits, key: 'parity'});
  
        if(configRow==1)
           setConfigRow(6);
      }else {
        sights.push({value: driver.ipport, key: 'ipport'});
    //    setConfigRow(1);
      }
    }
 }


  if(formVals.protocolConfig!=null&&formVals.protocolConfig!=''){
    let config=formVals.protocolConfig.replaceAll("{","[[").replaceAll("}","]]").replaceAll(",","],[").replaceAll("\":\"","\",\"");
 console.log(config)
   var sight=JSON.parse(config);
   console.log(config)
   for(let item of sight){
    console.log(item)
    sights.push({key:item[0],value:item[1]})
   }
   formVals.sights=sights;
 }


  const forward = () => setCurrentStep(currentStep + 1);

  const backward = () => setCurrentStep(currentStep - 1);

  const handleNext = async () => {
    const fieldsValue = await form.validateFields();

    Object.assign(formVals, fieldsValue);
   
    let configs = new Map();
    if (fieldsValue.sights) {
      fieldsValue.sights.map((item) => {
        if(configItem.indexOf(item.key)==-1)
          configs.set(item.key,item.value);
      })
      console.log(configs)
      let config= JSON.stringify([...configs]);
      config=config.replaceAll("[[","{").replaceAll("]]","}").replaceAll("\",\"","\":\"").replaceAll("],[",",");
      console.log(config)
      formVals.protocolConfig = config;
    
    }
    
  
    if (currentStep < 2) {
      forward();
    } else {
      if (formVals.onlineTime) {
        formVals.onlineTime = formVals.onlineTime.format('YYYY-MM-DD HH:mm:ss');
      }
      if (formVals.latestMaintenanceTime) {
        formVals.latestMaintenanceTime = formVals.latestMaintenanceTime.format('YYYY-MM-DD HH:mm:ss');
      }
      console.log(formVals)
      handleUpdate(formVals);
    }
  };

  const okHandle = async () => {
    const fieldsValue = await form.validateFields();
 
    fieldsValue.deviceId = formVals.deviceId;
    // if (fieldsValue.onlineTime) {
    //   fieldsValue.onlineTime = fieldsValue.onlineTime.format('YYYY-MM-DD HH:mm:ss');
    // }
   
    form.resetFields();
    handleUpdate(fieldsValue);
  };

  const getOption = (list: API.DictItem[]) => {
    if (!list || list.length < 1) {
      return (
        <Option key={''} value={''}>
          没有找到选项
        </Option>
      );
    }
    return list.map((item) => (
      <Option key={item.dictCode} value={item.dictCode}>
        {item.dictValue}
      </Option>
    ))
  }




  const changeDriver = (e,e1) =>{
    var sights=[];
    var driver= driverList[e1.key];
    if(driver.driverType==1){
      sights.push({value: driver.commandPort, key: 'commandPort'});
      sights.push({value: driver.dataBits, key: 'dataBits'});
      sights.push({value: driver.baudRate, key: 'baudRate'});
      sights.push({value: driver.stopBits, key: 'stopBits'});
      sights.push({value: driver.stopBits, key: 'parity'});
      sights.push({value: '', key: 'slaveId'});
      setConfigRow(6);
      form.setFieldsValue({sights});
    }else {
      sights.push({value: driver.ipport, key: 'ipport'});
      setConfigRow(1);
      form.setFieldsValue({sights}   );
    }
     
  }


  const renderFooter = () => {
    if (currentStep === 1) {
      return (
        <>
          <Button style={{ float: 'left' }} onClick={backward}>
            上一步
          </Button>
          <Button onClick={() => onCancel()}>取消</Button>
          <Button type="primary" onClick={() => handleNext()}>
            下一步
          </Button>
        </>
      );
    }
    if (currentStep === 2) {
      return (
        <>
          <Button style={{ float: 'left' }} onClick={backward}>
            上一步
          </Button>
          <Button onClick={() => onCancel()}>取消</Button>
          <Button type="primary" onClick={() => handleNext()}>
            完成
          </Button>
        </>
      );
    }
    return (
      <>
        <Button onClick={() => onCancel()}>取消</Button>
        <Button type="primary" onClick={() => handleNext()}>
          下一步
        </Button>
      </>
    );
  };

  const renderContent = () => {
    if (currentStep === 0) {
      return (
        <>
           <FormItem
          label="设备名称"
          name="deviceName"
          rules={[{ required: true, message: '请输入至少二个字符！', min: 2 }]}
          >
            <Input placeholder="请输入" autoComplete='off' />
          </FormItem>
          <FormItem
          label="设备位号"
          name="deviceNo"
          rules={[{ required: true, message: '请输入至少二个字符！', min: 2 }]}
          >
            <Input placeholder="请输入" autoComplete='off' />
          </FormItem>
          <FormItem
            label="所在区域"
            name="areaId"
            rules={[{ required: true, message: '请选择所在区域' }]}
          >
             <TreeSelect
            style={{ width: '100%' }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={arealist}
          
          
            placeholder="请选择所在区域"
            treeDefaultExpandAll
          />
          </FormItem>
          <FormItem
            label="设备类型"
            name="deviceTypeId"
            rules={[{ required: true, message: '请选择设备类型' }]}
          >
            <Select placeholder="请选择">
              {devicetype.map((item) => (
                <Option key={item.typeId} value={item.typeId}>
                  {item.typeName}
                </Option>
            ))}
            </Select>
          </FormItem>
          <FormItem
            label="设备驱动"
            name="driverId"
            rules={[{ required: true, message: '请选择设备驱动' }]}
          >
            <Select placeholder="请选择设备驱动"   onChange={(e,e1)=>changeDriver(e,e1)}>
            {driverList.map((item,index) => (
              <Option key={index} value={item.id}  >
                {item.name} 
              </Option>
           ))}
            </Select>
          </FormItem>
          <FormItem
            label="通讯协议类别"
            name="protocolType"
            rules={[{ required: true, message: '请选择通讯协议类别' }]}
          >
            <Select placeholder="请选择通讯协议类别" >
            {getOption(protocoltype)} 
            </Select> 
          </FormItem>
         
        
            <div style={{margin:'0 0 0 158px'}}>  
            <Form.List name="sights">
            {(fields, { add, remove }) => (
              <>
                {fields.map(field => (
                  <Space key={field.key} align="baseline">
                  
                    
                    <Form.Item
                      {...field}
                      {...formItemLayout}
                      style={{width:'220px'}}
                      name={[field.name, 'key']}
                      fieldKey={[field.fieldKey, 'key']}
                      rules={[{ required: true, message: '请输入配置名' }]}
                    >
                     { field.fieldKey< configRow&& field.fieldKey<5? <Input placeholder="请输入配置名" disabled  />:  <Input placeholder="请输入配置名" />} 
                    </Form.Item>
                    {field.name ==5&& configRow==6? <Form.Item
                      {...field}
                      {...formItemLayout}
                      style={{width:'220px'}}
                      name={[field.name, 'value']}
                      fieldKey={[field.fieldKey, 'value']}
                      rules={[{ required: true, message: '请输入配置值' }]}
                    >
                       <Input     placeholder="请输入配置值"/>
                    </Form.Item>:  
                      <Form.Item
                        {...field}
                        {...formItemLayout}
                        style={{width:'220px'}}
                        name={[field.name, 'value']}
                        fieldKey={[field.fieldKey, 'value']}
                        rules={[{ required: true, message: '请输入配置值' }]}
                        
                      >
                         { field.fieldKey< configRow? <Input placeholder="请输入配置值" disabled  />:  <Input placeholder="请输入配置值" />}  
                      </Form.Item> }   
                    {field.fieldKey>=configRow?
                    <MinusCircleOutlined onClick={() => remove(field.name)} />
                    :<></>
                    }
                  
                  </Space>
                ))}
               
               
                    <Button style={{ width: '448px'}} type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                    添加配置
                    </Button>
             
                
              </>
            )}
          </Form.List>
          </div>
        </>
      );
    }
    if (currentStep === 1) {
      return (
        <>
            <FormItem
          label="设备位置"
          name="devicePosition"
          rules={[{ message: '请输入至少二个字符！', min: 2 }]}
          >
            <Input placeholder="请输入" autoComplete='off' />
          </FormItem>
       
          <FormItem
          label="设备描述"
          name="deviceDesc"
          rules={[{ min: 5,max:255 }]}
     //     rules={[{ required: true, message: '请输入至少十个字符！', min: 10 }]}
        >
          <TextArea  placeholder="请输入" showCount maxLength={100}  />
        </FormItem>
       
        <FormItem
          label="启用状态"
          name="useState"
        >
          <Radio.Group >
            <Radio value={0} >
              不启用
            </Radio>
            <Radio value={1}>
              启用
            </Radio>
          </Radio.Group>
        </FormItem>
          <FormItem
          label="设备品牌"
          name="deviceBrand"
          rules={[{ message: '请输入至少二个字符！', min: 2 }]}
          >
            <Input placeholder="请输入" autoComplete='off' />
          </FormItem>
          <FormItem
          label="设备型号"
          name="deviceModel"
          rules={[{  message: '请输入至少二个字符！', min: 2 }]}
          >
            <Input placeholder="请输入" autoComplete='off' />
          </FormItem>
          <FormItem
          label="产品序列号"
          name="seriaNumber"
          rules={[{  message: '请输入至少二个字符！', min: 2 }]}
          >
            <Input placeholder="请输入" autoComplete='off' />
          </FormItem>
      
        <FormItem
            label="上线时间"
            name="onlineTime"
            rules={[]}
          >
            <DatePicker  format="YYYY-MM-DD HH:mm:ss"   showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }} placeholder='请选择上线时间' style={{ width: '100%' }} />
          </FormItem>
        
        </>);
    }
    return (
      <>
       <FormItem
            label="最新维保时间"
            name="latestMaintenanceTime"
            rules={[{ required: true}]}
          >
            <DatePicker  format="YYYY-MM-DD HH:mm:ss"   showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }} placeholder='请选择最新维保时间 ' style={{ width: '100%' }} />
          </FormItem>
          <FormItem
          label="供货商"
          name="supplier"
          >
            <Input placeholder="请输入"  />
          </FormItem>
          <FormItem
          label="供货商联系人姓名"
          name="supplierName"
          >
            <Input placeholder="请输入" />
          </FormItem>
          <FormItem
          label="供货商联系人电话"
          name="supplierPhone"
          rules={[{ validator: validatorMobile }]}
          >
            <Input placeholder="请输入"   />
          </FormItem>
      </>
    );
  }

  
  return (
    <Modal
      width={800}
      destroyOnClose
      title="编辑模块"
      footer={renderFooter()}
      visible={updateModalVisible}
      onOk={okHandle}
      onCancel={() => onCancel()}
      className={styles.deviceform}
      maskClosable={false}
    >
      <Steps style={{ marginBottom: 28 }} current={currentStep}>
        <Step title="基本信息1" />
        <Step title="基本信息2" />
        <Step title="基本信息3" />
      </Steps>
      <Form
        {...formLayout}
        form={form}
        initialValues={ Object.assign(formVals, {
          onlineTime:formVals.onlineTime!=null?moment(formVals.onlineTime):formVals.onlineTime, 
          latestMaintenanceTime:formVals.latestMaintenanceTime!=null?moment(formVals.latestMaintenanceTime):formVals.latestMaintenanceTime, 
          areaId:formVals.areaId?.toString()
        
        }) }
      >
        {renderContent()}
       </Form>
    </Modal>
  );
};

export default UpdateForm;
